package com.travel.rabbit.aop;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import com.travel.rabbit.entity.LogEntity;
import com.travel.rabbit.entity.Result;
import com.travel.rabbit.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 云澜
 * @date 2023/5/16 10:36 上午
 */

@Slf4j
@Aspect
@Component
public class LogAroundAspect extends LogAspect {

    @Resource
    private LogService logService;

    @Around("@annotation(logAround)")
    public Object doAround(ProceedingJoinPoint point, LogAround logAround){

        //开始时间
        long startTime = System.currentTimeMillis();

        //获取所有的参数
        String params = getParams(point);
        String params2 = getParams2(point);

        Object result = new Object();
        try {
            //执行方法，获取返回参数
            result = point.proceed();
            log.info("返回参数是：{}" , result);
        }catch (Throwable e){
            log.error(e.getMessage(),e);
        }

        String user = getUser(point);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();

        save(0L,user,logAround.keyName(),logAround.operationType(),params2,result,url,ip,excTime(startTime));
        return  result;
    }

    private void save(Long userId,String userName,String methodName,String option,String args,Object returnObj,String url,String ip,float execTime){
        LogEntity operationLogPojo = new LogEntity();
        operationLogPojo.setUserId(userId);
        operationLogPojo.setUserName(userName);
        operationLogPojo.setMethodName(methodName);
        operationLogPojo.setOperation(option);
        operationLogPojo.setOperationTime(new Date());
        operationLogPojo.setArgs(args);
        Object o = JSONUtil.toJsonStr(returnObj);
        Result r = JSONUtil.toBean(JSONUtil.toJsonStr(o),Result.class);

        if (r.getMessage().length() > 250){
            operationLogPojo.setReturnObj(r.getMessage().substring(0,250));
        }else {
            operationLogPojo.setReturnObj(r.getMessage());
        }
        operationLogPojo.setExcTime(execTime);
        operationLogPojo.setMapping(url);
        operationLogPojo.setIp(ip);
        logService.save(operationLogPojo);
    }
}
